package downloader

import (
	"crypto/aes"
	"crypto/cipher"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"net/url"
	"os"
	"strings"
)

type M3U8Parser struct {
	root *url.URL
	ts   []string
	key  string
}

func (m *M3U8Parser) Init(target *url.URL) error {
	m.root = target
	m.ts = make([]string, 0)
	data := mustGet(m.root.String())
	arr := strings.Split(data, "\n")
	if len(arr) == 0 {
		log.Println("[ ERROR ] failed to init root: ", m.root)
		return errors.New(` failed to init root`)
	}
	idx := arr[len(arr)-1]
	abs, _ := url.Parse(idx)
	tsURL := m.root.ResolveReference(abs)
	data = mustGet(tsURL.String())
	arr = strings.Split(data, "\n")
	for _, x := range arr {
		if strings.HasPrefix(x, "#") {
			continue
		}
		m.ts = append(m.ts, x)
	}

	k ,_:= tsURL.Parse(`key.key`)
	fmt.Println(k.String())
	key := mustGet(k.String())
	fmt.Println(key)
	os.Mkdir("./ts", 0777)
	for i, t := range m.ts {
		u, _ := tsURL.Parse(t)
		name := fmt.Sprintf("./ts/%d.ts", i)
		_, err := os.Stat(name)
		if err != nil {
			if os.IsNotExist(err) {
				key := mustGet(u.String())
				ioutil.WriteFile(name, []byte(key), 0777)
			}
		}
	}

	return nil
}


func AES128Decrypt(crypted, key, iv []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	if len(iv) == 0 {
		iv = key
	}
	blockMode := cipher.NewCBCDecrypter(block, iv[:blockSize])
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = pkcs5UnPadding(origData)
	return origData, nil
}

func pkcs5UnPadding(origData []byte) []byte {
	length := len(origData)
	unPadding := int(origData[length-1])
	return origData[:(length - unPadding)]
}
